'''
实现将表格中的数据读到对应的js或者php文件中
'''
import os,time,sys
import xlrd,re,json
from conf.setting import special_mark
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0,BASE_DIR)
from main_wt2excel import readFileData
from resolve_file import special_write_js

#需要导入的表格目录
ci18n_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
excel_dir = os.path.join(ci18n_dir,'excel_import')
excelList = os.listdir(excel_dir)  #所有excel文件名
en_files = os.listdir(os.path.join(os.path.dirname(ci18n_dir),'lang','en'))

#参数为源列表
def run(Language_list):
    while True:
        print(excelList)
        excel_filename = input('>>choose the filename need to translate:').strip()
        if not excel_filename in excelList:
            print(os.linesep)
            print('input error,please retry'.center(40,'-'))
            continue
        else:
            readExcel(excel_filename,Language_list)
            break
            



#读excel中的数据
'''参数说明
参数1： 需要读取的表格的文件名 zh-cn.xls
参数2： 语言列表
参数3：表格的列数
'''
def readExcel(filename,Language_list,table_num=7):
    fileAddr = os.path.join(excel_dir,filename)
    book = xlrd.open_workbook(fileAddr)
    sheet1 = book.sheet_by_index(0)
    cols_num = sheet1.ncols  #表格的列数
    rows_num = sheet1.nrows  #表格的行数
    #判断列数是否为定义的列数
    if not cols_num == table_num:
        err_message = 'The number of columns in a table is not equal to %s' % table_num
        write_err_log(err_message)
        return
    #翻译的语言
    language = sheet1.cell_value(rowx=0, colx=0).strip()  #语言 eg:zh-cn
    #print(cols_num, rows_num, language)
    if not language in Language_list:  #如果翻译的表格语言不在列表中，退出，写log日志
        err_message = 'language:%s is illegal in row(1)' % language
        write_err_log(err_message)
    else:

        data_obj = {}  #存储所有数据的对象
        for this_file in en_files:  #循环en文件夹下的文件名
            data_obj[this_file] = []

        for line in range(1,rows_num):
            tmp_obj = {}
            key = sheet1.cell_value(rowx=line, colx=0)  #key
            value1 = sheet1.cell_value(rowx=line, colx=1)  #key对应的英语值
            value2 = sheet1.cell_value(rowx=line, colx=2)  #翻译的值
            file_name = sheet1.cell_value(rowx=line, colx=3) #文件名
            phpnameOtrue = sheet1.cell_value(rowx=line, colx=4) #php函数名或者是否有{$jQuery}标志
            isList = sheet1.cell_value(rowx=line, colx=5) #key对一个的英语是否为list类型，如果是则为'list'
            mark_num = int(sheet1.cell_value(rowx=line, colx=6)) #特殊标记的个数

            #检查key、value1、value2、file_name是否有值
            if value1 == 0:
                value1 = 'false'
                value2 = 'false'
            if key and value1 and value2 and file_name:
                num = 0
                for mark in special_mark:
                    num += len(re.findall(mark,str(value1)))
                if not (num ==mark_num): #标记数量不相等
                    err_message = 'mark num is not corect in cell of row:%d col:1' % (line+1)
                    write_err_log(err_message)
                    return
                num = 0
                for mark in special_mark:
                    num += len(re.findall(mark,str(value2)))
                if not (num ==mark_num): #标记数量不相等
                    err_message = 'mark num is not corect in cell of row:%d col:2' % (line+1)
                    write_err_log(err_message)
                    return
                if isList.strip() == 'list': #为列表类型
                    value1 = value1.split(',')  #将字符串变为数组
                    value2 = value2.split(',')
            else:
                err_message = 'line %s in this table leave space cell' % (line+1)
                write_err_log(err_message)
                return

            tmp_obj = {
                "key" : key,
                "value1" : value1,
                "value2" : value2,
                "phpnameOtrue" : phpnameOtrue
            }
            tmp_obj = json.dumps(tmp_obj,ensure_ascii=False,indent=4)
            file_name1 = file_name.replace('_'+language+'.','_en.')
            if file_name1 in data_obj:
                data_obj[file_name1].append(tmp_obj)
            else:
                err_message = 'line %s filename:%s is incorrect' % ((line+1),file_name)

        #print(data_obj)
        '''数据全部保存在data_obj对象中了
        现在需要数据与原英语文件进行对比，以及写文件爱你数据
        '''
        print('start to output...'.center(50,'-'))
        print('0%'.center(50,'-'))
        for index,key in enumerate(data_obj):
            if compare_write(data_obj,language,key):
                print(('%d%%' % int((index+1)*100/len(data_obj)) ).center(50,'-'))
            else:
                return
             
        print('well done.')
        




#写错误日志函数
def write_err_log(err_message):
    print('>>error:'+err_message)
    print('please check your .xls file'.center(50,'-'))
    #日志目录
    logAddr = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'logs')
    log_filename = os.path.join(logAddr,time.strftime('%Y_%m_%d',time.localtime())+'.log')
    with open(log_filename, 'a',encoding='utf-8') as fo:
        time1 = time.strftime('%H:%M:%S ',time.localtime())
        fo.write(time1+err_message + os.linesep)

'''参数说明
参数1： 所有数据
参数2： 即将转换的语言 eg:zh-cn
'''
def compare_write(data_obj,language,ori_filename):
    #通过初步检查表格的信息，接下来需要与原英文文件对比
    #print(sys.getsizeof(data_obj))
    #ori_filename = 'validate_en.js'
    file_ext = ori_filename.split('.')[1]  #获取文件后缀名 js  php
    filename = ori_filename.replace('_en.'+file_ext,'')  #文件名
    gen_addr = os.path.dirname(ci18n_dir)
    file0 = os.path.join(gen_addr,'lang','en', ori_filename)
    filename = filename + '_' +language + '.' +file_ext #base_tr.js
    file1 = os.path.join(gen_addr,'lang_out', language)
    if not os.path.exists(file1):
        os.mkdir(file1)
    file1 = os.path.join(file1,filename)

    if ori_filename == 'validate_en.js':
        #print(ori_filename)
        # 直接放到另外一个文件的函数里处理
        return special_write_js(file0,file1,data_obj[ori_filename])
        

    ret_data1 = readFileData(file0)[0]  #读en源文件中的数据
    ret_data2 = data_obj[ori_filename]  #对象里存储的该对象的值
    #print(ret_data1,type(ret_data1))
    
    #首先判断两个对象的key数量是否相等
    #print(len(ret_data1) , len(ret_data2))
    if not (len(ret_data1) == len(ret_data2) ):
        err_message = 'The number of key-value pairs is incorrect,please check table.'
        write_err_log(err_message)
        return

    #判断表格中的key是否都与原英语文件中的key相同
    tmp_obj={}  #重新存储key_value形式对象
    phpnameOtrue = ''  #php函数名或者特殊标记
    for item in ret_data2:
        #item 类型变为了str
        item = json.loads(item)
        key = item['key']
        value1 = item['value1']
        value2 = item['value2']
        if value1 == 'false':
            value1 = False
        if value2 == 'false':
            value2 = False
        if type(value2)==float :  #判断是否为数字类型
            value2 = int(value2)

        phpnameOtrue = item['phpnameOtrue']

        tmp_obj[key] = value2
        if key in ret_data1: #有key相等
            pass
        else:
            err_message = 'key:%s is not in source file:%s.' % (key,ori_filename)
            write_err_log(err_message)
            return
        #判断英语翻译是否改动
        # 暂时没做
        
    
    #通过检验,现在可以写数据进文件了
    if file_ext == 'js':
        with open(file0,'r',encoding='utf-8') as f0:
            file_data0 = f0.read()
            match_data = re.findall('({[^\{\}]*})',file_data0)
            match_data = match_data[0]
            
            aa = json.dumps(tmp_obj, ensure_ascii=False, indent=4)
            file_data0 = file_data0.replace(match_data,aa)
            #写数据进文件
            with open(file1,'w',encoding='utf-8') as f1:
                f1.write(file_data0)

    elif file_ext == 'php':
        with open(file1,'w',encoding='utf-8') as f1:
            f1.write('<?php\n')
            f1.write('function '+phpnameOtrue+'(){\n')
            f1.write('\treturn array(\n')

            n = 0
            for key in tmp_obj:
                n +=1
                #判断键值中是否有'单引导
                if re.findall("'",tmp_obj[key]):  #有单引号则值用双引号包裹，否则用单引号包裹  
                    key_val = "'" + key +"'"+ ' => ' +'"'+tmp_obj[key]+'"'
                else:
                    key_val = "'" + key +"'"+ ' => ' +"'"+tmp_obj[key]+"'"
                #最后一个不能加,号
                if n == len(tmp_obj):
                    f1.write('\t\t'+key_val+'\n')
                else:
                    f1.write('\t\t'+key_val+',\n')

            f1.write('\t);\n')
            f1.write('}\n')
            f1.write('?>')
    
    return True
            


    


    
